/*
 * Copyright 2016 atnoce.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.atnoce.view;

import com.atnoce.Start;
import com.atnoce.core.CommonCore;
import com.atnoce.core.SecurityController;
import com.atnoce.db.ClassTypeDao;
import com.atnoce.db.ConfigDao;
import com.atnoce.db.PasswordDao;
import com.atnoce.pojo.DirType;
import com.atnoce.pojo.PasswordItem;
import com.atnoce.util.Cache;
import com.atnoce.util.CommonUtil;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.Calendar;
import javafx.collections.ObservableList;

import org.apache.commons.lang.StringUtils;


import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.stage.Stage;

public class PasswordItemEditController {

	@FXML
	private TextField username;
	@FXML
	private CheckBox autoGenerate;
	@FXML
	private TextField pass;
	@FXML
	private Button autoGenerateBtn;
	@FXML
	private ChoiceBox<DirType> classType;
	@FXML
	private TextArea beizhu;
	@FXML
	private Button saveBtn;
	@FXML
	private Button cancelBtn;
	@FXML
	private Button pwdGenSettingBtn;
	private Start start;
	private Stage dialogStage;
	private PasswordItem pdi;

	private boolean okClicked=false;

	private final ClassTypeDao ctd=new ClassTypeDao();
	private final PasswordDao pd=new PasswordDao();
	private final ConfigDao cd=new ConfigDao();

	public void setDialogStage(Stage dialogStage){
		this.dialogStage=dialogStage;
	}
	public void setStart(Start start){
		this.start=start;
	}
	public boolean isOkClicked(){
		return okClicked;
	}
	public void setPdi(PasswordItem pdi){
		this.pdi=pdi;
                if(!StringUtils.isBlank(pdi.getPassId())){
                    try {
                        username.setText(SecurityController.getSecurityInstence().AESdecrypt(pdi.getAccount(), Cache.key));
                        pass.setText(SecurityController.getSecurityInstence().AESdecrypt(pdi.getPasswordStr(), Cache.key));
                    } catch (Exception ex) {
                    }
                    beizhu.setText(pdi.getRemarkStr());
                    ObservableList<DirType> items = classType.getItems();
                    for(int a=0;a<items.size();a++){
                            DirType get = items.get(a);
                            if(StringUtils.equals(get.getDirId(), pdi.getDirTypeId())){
                                classType.getSelectionModel().select(a);
                                break;
                            }
                    }
                     saveBtn.setOnAction(e->updatePasswordItem());
                     saveBtn.setText("更新");
                 }else{
                    //根据用户当前选择的分类，设置选中的分类
                    ObservableList<DirType> items = classType.getItems();
                    for(int a=0;a<items.size();a++){
                            DirType get = items.get(a);
                            if(StringUtils.equals(get.getDirName(), Cache.INDEX_LEFT_SELECTED_DIRTYPE)){
                                classType.getSelectionModel().select(a);
                                break;
                            }
                    }
                }
	}
        
	@FXML
	private void initialize(){
		autoGenerate.setOnAction(e->{
				autoGenerateBtn.setDisable(!autoGenerate.isSelected());
				pwdGenSettingBtn.setDisable(!autoGenerate.isSelected());
		});
                pwdGenSettingBtn.setTooltip(CommonUtil.getTooltip("点击设置密码生成器",14));
                
		try{
                    //设置分类列表的值
                    classType.setItems(ctd.getDirTypes());
                    
                   
                        //classType.getSelectionModel().select(Cache.INDEX_LEFT_SELECTED_DIRTYPE);
		}catch(SQLException e){
			Alert alert=new Alert(AlertType.ERROR);
			alert.setTitle("错误");
			alert.setHeaderText(null);
			alert.setContentText("读取分类列表错误!");
			alert.showAndWait();
			//return;
		}catch(ClassNotFoundException e){
                    Alert alert=new Alert(AlertType.ERROR);
			alert.setTitle("错误");
			alert.setHeaderText(null);
			alert.setContentText("找不到数据库驱动!");
			alert.showAndWait();
                }

		saveBtn.setOnAction(e->saveHandler());
               // 如果修改的时候点击了取消，会报错，因为取消会返回false，窗口关闭后会执行对账号的解密，
               // 但是用户取消了修改操作，此时是不需要解密的
		cancelBtn.setOnAction(e->{
                        okClicked=false;
			dialogStage.close();
		});
		autoGenerateBtn.setOnAction(e->autoGenreBtnHandler());
		pwdGenSettingBtn.setOnAction(e->pwdGenSettingHandler());
                
                 
                
	}
        private void updatePasswordItem(){
           String selectedItem = classType.getSelectionModel().getSelectedItem().getDirName();
           if(!StringUtils.equals(selectedItem, pdi.getDirTypeId())){
               //需要删除列表中的项
           }
           
           if(isInputValid()){
		Cache.ADD_PASS_ITEM_SELECT_DIRTYPE=selectedItem;
		Alert alert;
                String ume=username.getText().trim();
                String pwd=pass.getText();
                        
               try {
                    pdi.setAccount(SecurityController.getSecurityInstence().AESencrypt(ume, Cache.key));
                   pdi.setPasswordStr(SecurityController.getSecurityInstence().AESencrypt(pwd, Cache.key));
               } catch (Exception ex) {
                   alert=new Alert(AlertType.ERROR);
			alert.setTitle("失败");
			alert.setHeaderText(null);
			alert.setContentText("修改失败!");
			alert.showAndWait();
			okClicked=false;
			dialogStage.close();
                        return;
               }
                pdi.setRemarkStr(beizhu.getText());
			
		//pdi.setDirTypeId(selectedItem);
		try {
                    if(pd.updatePasswordItem(pdi,selectedItem)){
			alert=new Alert(AlertType.INFORMATION);
			alert.setTitle("成功");
			alert.setHeaderText(null);
			alert.setContentText("修改成功!");
			alert.showAndWait();
			okClicked=true;
			dialogStage.close();
                    }else{
			alert=new Alert(AlertType.ERROR);
			alert.setTitle("失败");
			alert.setHeaderText(null);
			alert.setContentText("修改失败!");
			alert.showAndWait();
			okClicked=false;
			dialogStage.close();
                    }
		} catch (Exception e1) {
                    alert=new Alert(Alert.AlertType.ERROR);
                    alert.setHeaderText("保存失败");
                    alert.setContentText("修改密码条目时发生系统错误!");
                    alert.showAndWait();
		}

            }
        }
        /**
         * 密码生成器按钮处理函数
         */
	private void autoGenreBtnHandler(){
		try {
			String generPassStr = CommonCore.getGenerPassStr(cd.getOnepassConfig());
			pass.setText(generPassStr);
		} catch (SQLException e) {
                    Alert alert=new Alert(Alert.AlertType.ERROR);
                    alert.setHeaderText("生成失败");
                    alert.setContentText("生成器发生内部错误!");
                    alert.showAndWait();
		}catch(ClassNotFoundException e){
                    Alert alert=new Alert(Alert.AlertType.ERROR);
                    alert.setHeaderText("生成失败");
                    alert.setContentText("找不到数据库驱动!");
                    alert.showAndWait();
                }
	}
        /**
         * 保存密码条目
         */
	private void saveHandler(){
		String selectedItem = classType.getSelectionModel().getSelectedItem().getDirName();
		if(isInputValid()){
			Cache.ADD_PASS_ITEM_SELECT_DIRTYPE=selectedItem;
			Alert alert;
                        String ume=username.getText().trim();
                        String pwd=pass.getText();
                        
                    try {
                        pdi.setAccount(SecurityController.getSecurityInstence().AESencrypt(ume, Cache.key));
                        pdi.setPasswordStr(SecurityController.getSecurityInstence().AESencrypt(pwd, Cache.key));
                    } catch (Exception ex) {
                        alert=new Alert(Alert.AlertType.ERROR);
                            alert.setHeaderText("保存失败");
                            alert.setContentText("添加密码条目时发生系统错误!"+ex.getMessage());
                            alert.showAndWait();
                            return;
                    }
                    
			pdi.setPassId(CommonCore.getId());
			pdi.setRemarkStr(beizhu.getText());
			
			//pdi.setDirTypeId(selectedItem.getDirId());
			Calendar calendar=Calendar.getInstance();
			pdi.setCreateTime(LocalDate.of(calendar.get(Calendar.YEAR),
			calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DAY_OF_MONTH)));
			try {
				if(pd.addPasswordItem(pdi,selectedItem)){
					alert=new Alert(AlertType.INFORMATION);
					alert.setTitle("成功");
					alert.setHeaderText(null);
					alert.setContentText("添加成功!");
					alert.showAndWait();
					okClicked=true;
					dialogStage.close();
				}else{
					alert=new Alert(AlertType.ERROR);
					alert.setTitle("失败");
					alert.setHeaderText(null);
					alert.setContentText("添加失败!");
					alert.showAndWait();
					okClicked=false;
					dialogStage.close();
				}
			} catch (Exception e1) {
                            alert=new Alert(Alert.AlertType.ERROR);
                            alert.setHeaderText("保存失败");
                            alert.setContentText("添加密码条目时发生系统错误!");
                            alert.showAndWait();
			}

		}
	}
	private boolean isInputValid(){
		String errorMessage="";
		if(StringUtils.isBlank(username.getText().trim())){
			errorMessage+="用户名不能为空!\n";
		}
		if(StringUtils.isBlank(pass.getText())){
			errorMessage+="密码不能为空！\n";
		}
		if(classType.getSelectionModel().getSelectedItem()==null){
			errorMessage+="请选择分类！\n";
		}
                if(beizhu.getText().trim().length()>500){
                    errorMessage+="备注信息不能超过500字符\n";
                }
		if(errorMessage.length()==0){
			return true;
		}else{
			Alert alert = new Alert(AlertType.WARNING);
			alert.setTitle("发现问题");
			alert.setHeaderText(null);
			alert.setContentText(errorMessage);
			alert.showAndWait();

			return false;
		}

	}
	public void pwdGenSettingHandler(){
            start.showPwdGenSettingDialog();

	}
}
